<?php


namespace App\Utils;


use http\Env\Request;
use Illuminate\Container\Container;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;


class HtmlPage extends LengthAwarePaginator
{
    public function url($page)
    {
        if ($page <= 0) {
            $page = 1;
        }

        $path = rtrim($this->path, '/');

        // 如果路径中包含分页信息则正则替换页码，否则将页码信息追加到路径末尾
      /*  if (preg_match('/\/page\/\d+/', $path)) {
            $path = preg_replace('/\/page\/\d+/', '/page/' . $page, $path);
        } else {
            $path .= '/page/' . $page;
        }*/

        $paths = explode('_',$path);
        array_pop($paths);
        array_push($paths,$page.'.'.Arr::get(pathinfo($path),'extension','html'));
        //var_dump($paths);
        $this->path = implode('_', $paths);
        //var_dump($paths);


        if ($this->query) {
            $url = $this->path . (Str::contains($this->path, '?') ? '&' : '?')
                . http_build_query($this->query, '', '&')
                . $this->buildFragment();
        } elseif ($this->fragment) {
            $url = $this->path . $this->buildFragment();
        } else {
            $url = $this->path;
        }
        return $url;
    }

    protected function setCurrentPage($currentPage, $pageName)
    {
        if (!$currentPage && preg_match('/\/page\/(\d+)/', $this->path, $matches)) {
            $currentPage = $matches[1];
        }
        return $this->isValidPageNumber($currentPage) ? (int) $currentPage : 1;
    }

    public static function injectIntoBuilder()
    {
        /*
         * $perPage 每页显示多少条
         * $columns 查询的字段
         * $pageName 翻页链接的参数名
         * $page 当前页数
         * */
        Builder::macro('seoPaginate', function ($page=null, $perPage = 2, $columns=['*'], $pageName='page') {
            $perPage = $perPage ?: $this->model->getPerPage();

            $items = ($total = $this->toBase()->getCountForPagination())
                ? $this->forPage($page, $perPage)->get($columns)
                : $this->model->newCollection();

            $options = [
                'path' => Paginator::resolveCurrentPath(),
                'pageName' => $pageName
            ];

            return Container::getInstance()->makeWith(HtmlPage::class, compact(
                'items', 'total', 'perPage', 'page', 'options'
            ));
        });
    }
}
